package com.boarsoft.hibernate;

import java.io.Serializable;
import java.util.Properties;

import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.UUIDHexGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

/**
 * 自定义hibernate id生成器，如果手动分配id，则不再需要生成；如未手动分配，则生成uuid。
 * 
 * @author YangLiu
 * @CreateDate 2017年6月15日 下午3:43:20
 * @version 1.0
 * 
 * @UpdateUser YongHuaPang
 * @UpdateDate 2019年8月21日
 * @UpdateRemark 升级到Hibernate5
 */
public class AssignableUUIDGenerator extends UUIDHexGenerator {

	private String entityName;

	// @Override
	// public void configure(Type type, Properties params, Dialect d) throws
	// MappingException {
	// super.configure(type, params, d);
	// this.entityName = params.getProperty("entity_name");
	// if (this.entityName == null) {
	// throw new MappingException("no entity name");
	// }
	// }

	@Override
	public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
		// sep = ConfigurationHelper.getString("separator", params, "");
		super.configure(type, params, serviceRegistry);
		this.entityName = params.getProperty("entity_name");
		if (this.entityName == null) {
			throw new MappingException("no entity name");
		}
	}

	// @Override
	// public Serializable generate(SessionImplementor session, Object object)
	// throws HibernateException {
	// Serializable id = session.getEntityPersister(this.entityName,
	// object).getIdentifier(object, session);
	// if (id == null) {
	// id = super.generate(session, object);
	// }
	// return id;
	// }

	@Override
	public Serializable generate(SharedSessionContractImplementor session, Object obj) {
		Serializable id = session.getEntityPersister(this.entityName, obj).getIdentifier(obj, session);
		if (id == null) {
			id = super.generate(session, obj);
		}
		return id;
	}
}
